package com.log6z.dashborad.utils;

import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * @Author duxiaoming@e6yun.com
 * @Date 2021/04/07
 * @Description 单号生成工具类
 */
@Component
public class NumberGenUtil {

    @Autowired
    private RedisCache redisUtil;


    private static RedisCache redisUtil2;

    @PostConstruct
    public void init() {
        redisUtil2 = this.redisUtil;
    }

    /**
     * 单号类型枚举
     */
    public enum NumberTypeEnum {


        /**
         * 卸货任务
         */
        UNLOAD_APPOINTMENT_TASK_CODE("UYS","yyMMddHHmm",4),

        /**
         * 集装箱倒短任务
         */
        BOX_APPOINTMENT_TASK_CODE("BYS","yyMMddHHmm",4);
        /**
         * 前缀
         */
        public String prefix;
        /**
         * 日期格式
         */
        public String dateStr;
        /**
         * 随机数字长度
         */
        public Integer randomLength;

        NumberTypeEnum(String prefix, String dateStr, Integer randomLength) {
            this.prefix = prefix;
            this.dateStr = dateStr;
            this.randomLength = randomLength;
        }
    }

    /**
     * 根据单号类型获取单号
     * @param numberTypeEnum 单号类型
     * @return 单号
     */
    public static String getNumber(NumberTypeEnum numberTypeEnum) {

        String prefix = numberTypeEnum.prefix;
        String dateStr = DateUtil.format(new Date(), numberTypeEnum.dateStr);
        String increaseStr = redisUtil2.increaseStr(prefix + dateStr, numberTypeEnum.randomLength);

        return prefix + dateStr + increaseStr;
    }


    public static String getNewNumber(NumberTypeEnum numberTypeEnum) {
        String prefix = numberTypeEnum.prefix;
        String dateStr = DateUtil.format(new Date(), numberTypeEnum.dateStr);
        final long increase = redisUtil2.increase(prefix + dateStr, 1);
        redisUtil2.setExpireTime(prefix + dateStr, 24 * 60 * 60 * 1000L);
        return prefix + dateStr + increase;
    }


    /**
     * 获取预约编码
     * @param numberTypeEnum
     * @return 单号
     */
    public static String getAppointMentNumber(NumberTypeEnum numberTypeEnum) {
        String prefix = numberTypeEnum.prefix;
        String dateStr = DateUtil.format(new Date(), numberTypeEnum.dateStr);
        String dateFormatStr = DateUtil.format(new Date(), "yyMMdd");
        String increaseStr = redisUtil2.increaseStr(prefix + dateFormatStr, numberTypeEnum.randomLength);

        return prefix + dateStr + increaseStr;
    }

}